#!/bin/bash

# Dify知识库管理系统 - 系统验证脚本
# 验证所有组件是否正确配置和可用

echo "=========================================="
echo "Dify知识库管理系统 - 系统验证"
echo "=========================================="
echo ""

# 颜色定义
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

ERRORS=0
WARNINGS=0

# 检查函数
check_command() {
    local cmd=$1
    local name=$2
    local required_version=$3
    
    echo -n "检查 $name... "
    if command -v $cmd &> /dev/null; then
        version=$($cmd --version 2>&1 | head -n1)
        echo -e "${GREEN}✓ 已安装${NC}"
        echo "  版本: $version"
        if [ ! -z "$required_version" ]; then
            echo "  要求: $required_version"
        fi
    else
        echo -e "${RED}✗ 未安装${NC}"
        ERRORS=$((ERRORS + 1))
    fi
}

# 1. 检查必需软件
echo "=========================================="
echo "1. 检查必需软件"
echo "=========================================="
check_command "java" "Java" "JDK 21"
check_command "mvn" "Maven" "3.6+"
echo -n "检查 MySQL... "
if command -v mysql &> /dev/null; then
    version=$(mysql --version 2>&1 | head -n1)
    echo -e "${GREEN}✓ 已安装${NC}"
    echo "  版本: $version"
    echo "  要求: 8.0+"
elif lsof -Pi :3306 -sTCP:LISTEN -t >/dev/null 2>&1; then
    echo -e "${GREEN}✓ MySQL服务运行中 (端口3306)${NC}"
    echo "  注意: mysql命令行工具未找到，但服务正在运行"
else
    echo -e "${RED}✗ 未安装或未运行${NC}"
    ERRORS=$((ERRORS + 1))
fi
check_command "node" "Node.js" "16+"
check_command "npm" "npm" ""
echo ""

# 2. 检查Java版本
echo "=========================================="
echo "2. 检查Java版本"
echo "=========================================="
if command -v java &> /dev/null; then
    java_version=$(java -version 2>&1 | head -n1 | cut -d'"' -f2 | cut -d'.' -f1)
    if [ "$java_version" -ge 21 ]; then
        echo -e "${GREEN}✓ Java版本符合要求 (>= 21)${NC}"
    else
        echo -e "${RED}✗ Java版本过低 (当前: $java_version, 要求: 21)${NC}"
        ERRORS=$((ERRORS + 1))
    fi
else
    echo -e "${RED}✗ Java未安装${NC}"
    ERRORS=$((ERRORS + 1))
fi
echo ""

# 3. 检查MySQL连接
echo "=========================================="
echo "3. 检查MySQL连接"
echo "=========================================="
if command -v mysql &> /dev/null; then
    if mysql -h localhost -P 3306 -u root -proot -e "SELECT 1" &> /dev/null; then
        echo -e "${GREEN}✓ MySQL连接成功${NC}"
        
        # 检查数据库是否存在
        if mysql -h localhost -P 3306 -u root -proot -e "USE dify_knowledge_system; SELECT 1" &> /dev/null; then
            echo -e "${GREEN}✓ 数据库 dify_knowledge_system 已存在${NC}"
            
            # 检查表是否存在
            table_count=$(mysql -h localhost -P 3306 -u root -proot -D dify_knowledge_system -e "SHOW TABLES" 2>/dev/null | wc -l)
            if [ $table_count -gt 7 ]; then
                echo -e "${GREEN}✓ 数据库表已创建 ($((table_count - 1))张表)${NC}"
            else
                echo -e "${YELLOW}⚠ 数据库表可能未完全创建${NC}"
                echo "  请运行: mysql -u root -p < init-database.sql"
                WARNINGS=$((WARNINGS + 1))
            fi
        else
            echo -e "${YELLOW}⚠ 数据库 dify_knowledge_system 不存在${NC}"
            echo "  请运行: mysql -u root -p < init-database.sql"
            WARNINGS=$((WARNINGS + 1))
        fi
    else
        echo -e "${RED}✗ MySQL连接失败${NC}"
        echo "  请检查MySQL服务是否运行，用户名密码是否正确"
        ERRORS=$((ERRORS + 1))
    fi
elif lsof -Pi :3306 -sTCP:LISTEN -t >/dev/null 2>&1; then
    echo -e "${GREEN}✓ MySQL服务运行中 (端口3306)${NC}"
    echo -e "${YELLOW}⚠ mysql命令行工具未找到，无法验证数据库${NC}"
    echo "  建议: 安装MySQL客户端或使用GUI工具验证数据库"
    WARNINGS=$((WARNINGS + 1))
else
    echo -e "${RED}✗ MySQL服务未运行${NC}"
    echo "  请启动MySQL服务"
    ERRORS=$((ERRORS + 1))
fi
echo ""

# 4. 检查项目文件
echo "=========================================="
echo "4. 检查项目文件"
echo "=========================================="
files=(
    "pom.xml:Maven配置文件"
    "src/main/resources/application.yml:应用配置文件"
    "src/main/java/com/dify/knowledge/DifyKnowledgeSystemApplication.java:主应用类"
    "init-database.sql:数据库初始化脚本"
    "frontend/package.json:前端配置文件"
    "frontend/src/main.js:前端入口文件"
)

for file_info in "${files[@]}"; do
    IFS=':' read -r file desc <<< "$file_info"
    echo -n "检查 $desc... "
    if [ -f "$file" ]; then
        echo -e "${GREEN}✓ 存在${NC}"
    else
        echo -e "${RED}✗ 不存在${NC}"
        ERRORS=$((ERRORS + 1))
    fi
done
echo ""

# 5. 检查后端编译
echo "=========================================="
echo "5. 检查后端编译"
echo "=========================================="
echo "正在编译后端项目..."
if mvn clean compile -DskipTests -q; then
    echo -e "${GREEN}✓ 后端编译成功${NC}"
else
    echo -e "${RED}✗ 后端编译失败${NC}"
    ERRORS=$((ERRORS + 1))
fi
echo ""

# 6. 检查前端依赖
echo "=========================================="
echo "6. 检查前端依赖"
echo "=========================================="
if [ -d "frontend/node_modules" ]; then
    echo -e "${GREEN}✓ 前端依赖已安装${NC}"
else
    echo -e "${YELLOW}⚠ 前端依赖未安装${NC}"
    echo "  请运行: cd frontend && npm install"
    WARNINGS=$((WARNINGS + 1))
fi
echo ""

# 7. 检查配置文件
echo "=========================================="
echo "7. 检查配置文件"
echo "=========================================="
if [ -f "src/main/resources/application.yml" ]; then
    echo "检查Dify API配置..."
    if grep -q "key: # TODO" src/main/resources/application.yml; then
        echo -e "${YELLOW}⚠ Dify API密钥未配置${NC}"
        echo "  请在 application.yml 中配置 dify.api.key"
        WARNINGS=$((WARNINGS + 1))
    else
        echo -e "${GREEN}✓ Dify API密钥已配置${NC}"
    fi
    
    echo "检查数据库配置..."
    if grep -q "password: root" src/main/resources/application.yml; then
        echo -e "${GREEN}✓ 数据库密码已配置${NC}"
    else
        echo -e "${YELLOW}⚠ 数据库密码可能需要修改${NC}"
        WARNINGS=$((WARNINGS + 1))
    fi
fi
echo ""

# 8. 检查端口占用
echo "=========================================="
echo "8. 检查端口占用"
echo "=========================================="
check_port() {
    local port=$1
    local service=$2
    
    echo -n "检查端口 $port ($service)... "
    if lsof -Pi :$port -sTCP:LISTEN -t >/dev/null 2>&1; then
        echo -e "${YELLOW}⚠ 已被占用${NC}"
        WARNINGS=$((WARNINGS + 1))
    else
        echo -e "${GREEN}✓ 可用${NC}"
    fi
}

check_port 8080 "后端服务"
check_port 5173 "前端服务"
check_port 3306 "MySQL"
echo ""

# 9. 检查文件权限
echo "=========================================="
echo "9. 检查文件权限"
echo "=========================================="
scripts=("start-all.sh" "stop-all.sh" "test-integration.sh")
for script in "${scripts[@]}"; do
    echo -n "检查 $script 执行权限... "
    if [ -x "$script" ]; then
        echo -e "${GREEN}✓ 可执行${NC}"
    else
        echo -e "${YELLOW}⚠ 不可执行${NC}"
        echo "  请运行: chmod +x $script"
        WARNINGS=$((WARNINGS + 1))
    fi
done
echo ""

# 10. 检查上传目录
echo "=========================================="
echo "10. 检查上传目录"
echo "=========================================="
echo -n "检查上传目录... "
if [ -d "uploads" ]; then
    echo -e "${GREEN}✓ 已存在${NC}"
else
    echo -e "${YELLOW}⚠ 不存在，将在首次上传时自动创建${NC}"
    WARNINGS=$((WARNINGS + 1))
fi
echo ""

# 总结
echo "=========================================="
echo "验证结果总结"
echo "=========================================="
if [ $ERRORS -eq 0 ] && [ $WARNINGS -eq 0 ]; then
    echo -e "${GREEN}✓ 所有检查通过！系统已准备就绪。${NC}"
    echo ""
    echo "下一步："
    echo "  1. 启动服务: ./start-all.sh"
    echo "  2. 访问前端: http://localhost:5173"
    echo "  3. 运行测试: ./test-integration.sh"
    exit 0
elif [ $ERRORS -eq 0 ]; then
    echo -e "${YELLOW}⚠ 发现 $WARNINGS 个警告${NC}"
    echo ""
    echo "系统可以运行，但建议解决上述警告。"
    echo ""
    echo "下一步："
    echo "  1. 解决警告（可选）"
    echo "  2. 启动服务: ./start-all.sh"
    exit 0
else
    echo -e "${RED}✗ 发现 $ERRORS 个错误和 $WARNINGS 个警告${NC}"
    echo ""
    echo "请解决上述错误后再启动系统。"
    exit 1
fi
